<?

	require_once('lib/OwnedObject.php');

	class Article extends OwnedObject{
			protected $modelName = 'Article';
			protected $content='';
			protected $category;
			protected $link;
			protected $title='';


			public static function Install() {
                    OwnedObject::Install();
					$query=sprintf("CREATE TABLE `Article` (
									`Id` INT( 32 ) unsigned NOT NULL ,
									`content` TEXT ,
									`Category` INT(32) unsigned NOT NULL ,
									`link` VARCHAR(30),
									`title` VARCHAR(20),
									PRIMARY KEY ( `Id` ),
									FOREIGN KEY (`Id`) REFERENCES `Object`(`id`) ON DELETE CASCADE,
									FOREIGN KEY (`Category`) REFERENCES `Category`(`id`)
									) ENGINE=INNODB DEFAULT CHARSET=utf8;
								");
					mysql_query($query);

					$query = sprintf("INSERT INTO `ObjectType` SET `name` = '%s'", strval(__CLASS__));
                        mysql_query($query);
					echo "Articles installed\n";
			}

			public function Load() {
                        
                        if(!isset($this->link)){
	                        $query = sprintf("SELECT
													`Id`, `content`, `Category`, `link`, `title`
											FROM
												`Article`
											WHERE
												`Id` =%d", $this->id);
                        }
                        else {
                        	$query = sprintf("SELECT
													`Id`, `content`, `Category`, `link`, `title`
											FROM
												`Article`
											WHERE
												`link` ='%s'", $this->link);
                        }
                        $res = mysql_query($query);
                        $row = mysql_fetch_array($res);
			
                        $this->id = $row[0];
                        
                         parent::Load();
                        
                        $this->content = $row[1];
                        $this->category = $row[2];
                        $this->link = $row[3];
                        $this->title = $row[4];
                       
           }

			public function AsSource($otherName = 'Article'){
						$result = parent::AsSource($otherName);

						$content = new XmlSource('content',$this->content);
						
						$result -> MountSource($content);
						$result -> Attribute('link',$this->link);
						$result -> Attribute('title',$this->title);
						$result -> Attribute('parent', $this->category);
						if(replace_link($_SERVER['REQUEST_URI']) == "article/".$this->Link()){
								$result -> Attribute('selected','selected');
						}

						return $result;
			}

			public function Content($newContent=false) {
                        if($newContent)
                                $this->content = $newContent;
                        return $this->content;
            }
            
            public function Link($newLink=false) {
                        if($newLink)
                                $this->link = $newLink;
                        return $this->link;
            }
            
            public function Title($newTitle=false) {
                        if($newTitle)
                                $this->title = $newTitle;
                        return $this->title;
            }

			public function Category($newCategory=false) {
            	if($newCategory){
					if($newCategory instanceof Category)
                    	$this->category = $newCategory->Id();
                    else throw new Exception("Invalid argument, Category instance required");
            	}
              	$cat = new Category($this->category);
              	if(!$newCategory) $cat->Load();
                return $cat;
            }            

			public function RegisterObject(){
						$obj_id= parent::RegisterObject();
						$query=sprintf("INSERT INTO
												`Article` ( `Id` , `content`, `Category`,`link`, `title` )
											VALUES (%d, '%s', %d, '%s', '%s')
							", $obj_id, $this->content, $this->category, $this->link, $this->title);
						mysql_query($query);
			}


			public function Save(){
						if($this->id<1){
							$this->RegisterObject();
						}
						else{
							$query=sprintf("UPDATE `Article`
											SET
												  `content`= '%s',
												  `Category`= %d,
												  `link` = '%s',
												  `title` = '%s'
											WHERE `Id`=%d", $this->content, $this->category, $this->link, $this->title, $this->id);
							mysql_query($query);
						}
			}


			public function Remove(){
				$query=sprintf("DELETE FROM `Article` WHERE Id=%d",$this->id);
				mysql_query($query);
				parent::Remove();
			}
			
//////////////////////////////////************************\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
			public static function CreateNewsFish($num){
				$act = array('Внимание-внимание!!!', 'Уважаемые дамы и гоподЫ!');
				$time = array('Вчера ', 'Сегодня ', 'Год назад ');
				$subs = array('конь ','собака ','порталл ','погода ','кошка ');
				$verbs = array('мурлыкнула ','гавкнула ','тикнула ', 'прыг ', 'не смог прийти на совещание');
				$prefix = array('О ', 'Про ', 'Новость о ');


				$ac = count($act)-1;
				$tc = count($time)-1;
				$sc = count($subs)-1;
				$vc = count($verbs)-1;
				$pc = count($prefix)-1;

				for($i=0;$i<$num;$i++){
					sleep(1);
					$s = rand(0,$sc);
					$v = rand(0,$vc);
					$title=$prefix[rand(0,$pc)].$subs[$s];
					$announce = $subs[$s].$verbs[$v];
					$content = '';
					$content .= $act[rand(0,$ac)]; $content = '<h3>'.$content.'</h3>';
					$content .= '<p>'.$time[rand(0,$tc)].$subs[$s].$verbs[$v].'</p>';


					$nm = new News();
					$nm->Title($title);
					$nm->Announce($announce);
					$nm->Content($content);
					$nm->Save();
				}
			}
			
			//Новости по количеству
			public static function NewsByCount($num=8,$offset=0){
					$query = sprintf("SELECT n.`Id` 
					FROM `News` n, `Object` o 
					WHERE n.`Id`=o.`id` and `status`=%d ORDER BY o.`created` DESC
					LIMIT %d, %d", NEWS_STATUS_ACTUAL, $offset, $offset+$num);
					$parse = mysql_query($query);

					$news_list = new XmlSource('News-list');
					while($result = mysql_fetch_assoc($parse)){
						
						$n_id = $result['Id'];
						$news = new News($n_id);
						$news->Load();
						$news_list->MountSource($news->AsSource());
					}
					
					//mount pages
					$query = sprintf("SELECT count(1) FROM `News`
					WHERE `status`=%d", NEWS_STATUS_ACTUAL);
					$res = mysql_query($query);
					$row = mysql_fetch_row($res);
					$news_count = $row[0];
					
					$pages_count = (int)$news_count/$num;
					$selected_page = (int)$offset / $num + 1;
					
					$pages = new XmlSource('pages');
					for($i=1; $i<=$pages_count; $i++){
						$p_link = new XmlSource('page');
						$p_link->Attribute('num', $i);
						if($i == $selected_page) $p_link->Attribute('selected', 'selected');
						$pages->MountSource($p_link);
					}
					
					$news_list->MountSource($pages);

					return $news_list;
			}			

	}

?>